//
//  LLNavigationController.swift
//  LLNavigationBar
//
//  Created by 若望 on 2020/7/6.
//  Copyright © 2020 若望. All rights reserved.
//

import UIKit

fileprivate func isImageEqual(_ img1: UIImage?, _ img2: UIImage?) -> Bool {
    guard let image1 = img1, let image2 = img2 else {
        return false
    }
    if image1 == image2 {
        return true
    }
    guard let data1 = image1.pngData(), let data2 = image2.pngData() else {
        return false
    }
    return data1 == data2
}

fileprivate func shouldShowFake(vc: UIViewController, from: UIViewController, to: UIViewController) -> Bool {
    if vc != to {
        return false
    }
    if let fromCBIMage = from.llComputedBarImage, let toCBIMage = to.llComputedBarImage {
        if isImageEqual(fromCBIMage, toCBIMage) || fromCBIMage.description == toCBIMage.description {
            if abs(from.llBarAlpha - to.llBarAlpha) > 0.1 {
                return true
            }
            return false
        }
    }
    return true
}
fileprivate func colorHasAlphaComponent(_ color: UIColor?) -> Bool {
    guard let c = color else {
        return true
    }
    var red: CGFloat = 0.0
    var green: CGFloat = 0.0
    var blue: CGFloat = 0.0
    var alpha: CGFloat = 0.0
    c.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
    return alpha < 1.0
}
fileprivate func imageHasAlphaChannel(_ image: UIImage?) -> Bool {
    guard let img = image, let alpha = img.cgImage?.alphaInfo else {
        return false
    }
    return (alpha == CGImageAlphaInfo.first ||
        alpha == CGImageAlphaInfo.last ||
        alpha == CGImageAlphaInfo.premultipliedFirst ||
        alpha == CGImageAlphaInfo.premultipliedLast)
}
fileprivate func adjustLayout(_ vc : UIViewController) {
    var isTranslucent: Bool = vc.llBarHidden || vc.llBarAlpha < 1.0
    if !isTranslucent {
        if let iamge = vc.llComputedBarImage {
            isTranslucent = imageHasAlphaChannel(iamge)
        }else {
            let color = vc.llComputedBarTintColor
            isTranslucent = colorHasAlphaComponent(color)
        }
    }
    if isTranslucent || vc.extendedLayoutIncludesOpaqueBars {
        vc.edgesForExtendedLayout = UIRectEdge(rawValue: vc.edgesForExtendedLayout.rawValue | UIRectEdge.top.rawValue)
    }else {
        vc.edgesForExtendedLayout = UIRectEdge(rawValue: vc.edgesForExtendedLayout.rawValue & ~UIRectEdge.top.rawValue)
    }
    if vc.llBarHidden, #available(iOS 11.0, *) {
        let insets = vc.additionalSafeAreaInsets
        let height: CGFloat = LLNaviScreenSize.naviBarHeight
        vc.additionalSafeAreaInsets = UIEdgeInsets.init(top: -height + insets.top, left: insets.left, bottom: insets.bottom, right: insets.right)
    }
    
}
fileprivate func blendColor(_ from: UIColor, _ to: UIColor, _ percent: CGFloat) -> UIColor {
    var fromRed: CGFloat = 0.0
    var fromGreen: CGFloat = 0.0
    var fromBlue: CGFloat = 0.0
    var fromAlpha: CGFloat = 0.0
    from.getRed(&fromRed, green: &fromGreen, blue: &fromBlue, alpha: &fromAlpha)
    
    var toRed: CGFloat = 0.0
    var toGreen: CGFloat = 0.0
    var toBlue: CGFloat = 0.0
    var toAlpha: CGFloat = 0.0
    to.getRed(&toRed, green: &toGreen, blue: &toBlue, alpha: &toAlpha)
    
    let newRed: CGFloat = fromRed + (toRed - fromRed) * CGFloat(fminf(1, Float(percent * 4.0)))
    let newGreen: CGFloat = fromGreen + (toGreen - fromGreen) * CGFloat(fminf(1, Float(percent * 4.0)))
    let newBlue: CGFloat = fromBlue + (toBlue - fromBlue) * CGFloat(fminf(1, Float(percent * 4.0)))
    let newAlpha: CGFloat = fromAlpha + (toAlpha - fromAlpha) * CGFloat(fminf(1, Float(percent * 4.0)))
    return UIColor.init(red: newRed, green: newGreen, blue: newBlue, alpha: newAlpha)
}


/// 屏幕尺寸
struct LLNaviScreenSize {
    static var statusBarHeight: CGFloat {
        //return UIApplication.shared.statusBarFrame.height == 44 ? 88 : 64
        return LLNaviScreenSize.isFullScreen ? 44 : 20
    }
    
    static var naviBarHeight: CGFloat {
        //return UIApplication.shared.statusBarFrame.height == 44 ? 88 : 64
        return LLNaviScreenSize.statusBarHeight + 44.0
    }
    
    static var bottomSafeHeight: CGFloat {
        return LLNaviScreenSize.isFullScreen ? 34 : 0
    }
    
    fileprivate static var isFullScreen: Bool {
        if #available(iOS 11, *) {
            guard let w = UIApplication.shared.delegate?.window, let unwrapedWindow = w else {
                return false
            }
            
            if unwrapedWindow.safeAreaInsets.left > 0 || unwrapedWindow.safeAreaInsets.bottom > 0 {
                print(unwrapedWindow.safeAreaInsets)
                return true
            }
        }
        return false
    }
}



public class LLNavigationControllerDelegate: NSObject, UINavigationControllerDelegate, UIGestureRecognizerDelegate {
    public weak var proxiedDelegate: UINavigationControllerDelegate!
    public weak var nav: LLNavigationController!
    
    convenience init(navigationController: LLNavigationController) {
        self.init()
        self.nav = navigationController
        self.nav?.delegate = self
        self.nav?.superInteractivePopGestureRecognizer?.delegate = self
        self.nav?.superInteractivePopGestureRecognizer?.addTarget(self, action: #selector(handleNavigationTransition(pan:)))
    }
    
    public func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
        if self.nav.viewControllers.count > 1 {
            if let topViewController = self.nav.topViewController {
                return topViewController.llSwipeBackEnabled && topViewController.llBackInteractive
            }
        }
        return false
    }
    
    @objc func handleNavigationTransition(pan: UIScreenEdgePanGestureRecognizer) {
        
        if #available(iOS 11.0, *) {
        } else{
            if let coordinator = nav.transitionCoordinator {
                if let from = coordinator.viewController(forKey: UITransitionContextViewControllerKey.from), let to = coordinator.viewController(forKey: UITransitionContextViewControllerKey.to) {
                    if pan.state == .began || pan.state == .changed {
                        nav.navigationBar.tintColor = blendColor(from.llTintColor, to.llTintColor, coordinator.percentComplete)
                    }
                }
            }
        }
    }
    
    public func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
        self.proxiedDelegate?.navigationController?(navigationController, willShow: viewController, animated: animated)
        
        let nav = self.nav
        nav?.transitional = true
        
        if !(viewController.llExtendedLayoutDidSet) {
            adjustLayout(viewController)
            viewController.llExtendedLayoutDidSet = true
        }
        
        if let coordinator = nav?.transitionCoordinator {
            if #available(iOS 11.0, *) {
                if let from = coordinator.viewController(forKey: UITransitionContextViewControllerKey.from), let to = coordinator.viewController(forKey: UITransitionContextViewControllerKey.to) {
                    if from == nav?.poppingViewController, to.navigationController == nav {
                        
                        let newButtonItem = UIBarButtonItem.init()
                        if let odlButtonItem = to.navigationItem.backBarButtonItem {
                            newButtonItem.title = odlButtonItem.title
                        }else {
                            newButtonItem.title = nav?.llNavigationBar?.backButtonLabel?.text
                        }
                        newButtonItem.tintColor = from.llTintColor
                        to.navigationItem.backBarButtonItem = newButtonItem
                    }
                    if let top = nav?.topViewController, let _ =  top.navigationItem.backBarButtonItem, nav?.poppingViewController != nil {
                        top.llBackBarButtonItem = top.navigationItem.backBarButtonItem
                        if to == top, from.navigationController == nav {
                            if let backItem = from.navigationItem.backBarButtonItem {
                                backItem.tintColor = to.llTintColor;
                            }
                        }
                    }
                }
            }
            self.showViewController(viewController, coordinator)
        }else {
            if !animated && (nav?.children.count ?? 1) > 1 {
                if let lastButOne = nav?.children[(nav?.children.count ?? 2) - 2], shouldShowFake(vc: viewController, from: lastButOne, to: viewController) {
                    nav?.showFakeBarFrom(lastButOne, viewController)
                    return;
                }
            }
            nav?.updateNavigationBarForViewController(viewController)
        }
        
    }
    
    public func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) {
        self.proxiedDelegate?.navigationController?(navigationController, didShow: viewController, animated: animated)
        nav?.transitional = false
        if !animated {
            nav?.updateNavigationBarForViewController(viewController)
            nav?.clearFake()
        }
        
        if #available(iOS 11.0, *) {
            if let llBackBarButtonItem = viewController.llBackBarButtonItem {
                viewController.navigationItem.backBarButtonItem = llBackBarButtonItem
            }
        }
        nav.poppingViewController = nil
    }
    
    public func navigationControllerSupportedInterfaceOrientations(_ navigationController: UINavigationController) -> UIInterfaceOrientationMask {
        return self.proxiedDelegate?.navigationControllerSupportedInterfaceOrientations?(navigationController) ?? UIInterfaceOrientationMask.portrait
    }
    
    public func navigationControllerPreferredInterfaceOrientationForPresentation(_ navigationController: UINavigationController) -> UIInterfaceOrientation {
        return self.proxiedDelegate?.navigationControllerPreferredInterfaceOrientationForPresentation?(navigationController) ?? UIInterfaceOrientation.portrait
    }
    
    public func navigationController(_ navigationController: UINavigationController, interactionControllerFor animationController: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
        return self.proxiedDelegate?.navigationController?(navigationController, interactionControllerFor: animationController) ?? nil
    }
    
    public func navigationController(_ navigationController: UINavigationController, animationControllerFor operation: UINavigationController.Operation, from fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        return self.proxiedDelegate?.navigationController?(navigationController, animationControllerFor: operation, from: fromVC, to: toVC) ?? nil
    }
    
    
    
    public func showViewController(_ viewController: UIViewController, _ coordinator: UIViewControllerTransitionCoordinator) {
        guard let from = coordinator.viewController(forKey: UITransitionContextViewControllerKey.from), let to = coordinator.viewController(forKey: UITransitionContextViewControllerKey.to) else {
            return
        }
        // Fix a system bug https://github.com/listenzz/HBDNavigationBar/issues/35
        if #available(iOS 12.0, *) {
            if let navBar = self.nav?.navigationBar {
                self.resetButtonLabelInNavBar(navBar: navBar)
            }
            
        }
        self.nav?.updateNavigationBarAnimatedForViewController(viewController)
        coordinator.animate(alongsideTransition: { (context) in
            let shouldFake = shouldShowFake(vc: viewController, from: from, to: to)
            if shouldFake {
                // title attributes, button tint colo, barStyle
                self.nav?.updateNavigationBarAnimatedForViewController(viewController)
                
                // background alpha, background color, shadow image alpha
                self.nav?.showFakeBarFrom(from, to)
            } else {
                self.nav?.updateNavigationBarForViewController(viewController)
            }
        }) { (context) in
            self.nav.transitional = false
            self.nav.poppingViewController = nil
            if context.isCancelled {
                if to == viewController {
                    self.nav?.updateNavigationBarForViewController(from)
                }
            } else {
                // `to` != `viewController` when present
                self.nav?.updateNavigationBarForViewController(viewController)
            }
            if to == viewController {
                self.nav?.clearFake()
            }
        }
    }
    
    
    public func resetButtonLabelInNavBar(navBar: UINavigationBar) {
        if #available(iOS 12.0, *) {
            for view in navBar.subviews {
                let viewName = view.classForCoder.description().replacingOccurrences(of: "_", with: "")
                if viewName == "UINavigationBarContentView" {
                    self.resetButtonLabelInView(view: view)
                    break
                }
            }
        }
    }
    public func resetButtonLabelInView(view: UIView) {
        let viewName = view.classForCoder.description().replacingOccurrences(of: "_", with: "")
        if viewName == "UIButtonLabel" {
            view.alpha = 1.0
        } else if view.subviews.count > 0 {
            for sub in view.subviews {
                self.resetButtonLabelInView(view: sub)
            }
        }
    }
}


public class LLNavigationController: UINavigationController {
    public var transitional: Bool = false
    public weak var poppingViewController: UIViewController?
    public var llNavigationBar: LLNavigationBar? {
        return self.navigationBar as? LLNavigationBar
    }
    
    
    public var fromFakeBar: UIVisualEffectView?
    public var toFakeBar: UIVisualEffectView?
    public var fromFakeShadow: UIImageView?
    public var toFakeShadow: UIImageView?
    public var fromFakeImageView: UIImageView?
    public var toFakeImageView: UIImageView?
    public var navigationDelegate: LLNavigationControllerDelegate?
    
    private func setupDelegate(_ del: UINavigationControllerDelegate?) {
        if (del != nil && del!.isKind(of: LLNavigationControllerDelegate.self)) || self.navigationDelegate != nil {
            self.delegate = del
        }else{
            self.navigationDelegate?.proxiedDelegate = del
        }
    }

    public var superInteractivePopGestureRecognizer: UIGestureRecognizer? {
        return self.interactivePopGestureRecognizer
    }
    
    public override var childForStatusBarHidden: UIViewController? {
        return self.topViewController
    }
    
    public override init(rootViewController: UIViewController) {
        super.init(navigationBarClass: LLNavigationBar.self, toolbarClass: UIToolbar.self)
        self.viewControllers = [rootViewController]
    }
    
    public required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    public override init(navigationBarClass: AnyClass?, toolbarClass: AnyClass?) {
        assert((navigationBarClass?.isSubclass(of: LLNavigationBar.self) ?? false), "navigationBarClass Must be a subclass of HBDNavigationBar")
        super.init(navigationBarClass: navigationBarClass, toolbarClass: toolbarClass)
    }
    
    public init() {
        super.init(navigationBarClass: LLNavigationBar.self, toolbarClass: UIToolbar.self)
    }
    
    public override func viewDidLoad() {
        super.viewDidLoad()
        self.navigationBar.isTranslucent = true
        self.navigationBar.shadowImage = UINavigationBar.appearance().shadowImage
        
        self.navigationDelegate = LLNavigationControllerDelegate.init(navigationController: self)
        self.setupDelegate(self.navigationDelegate)
    }
    
    public override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
        if self.transitionCoordinator != nil, let top = self.topViewController {
            self.updateNavigationBarForViewController(top)
        }
    }
    
    public override func popViewController(animated: Bool) -> UIViewController? {
        self.poppingViewController = self.topViewController
        let vc = super.popViewController(animated: animated)
        // vc != self.topViewController
        self.fixClickBackIssue()
        return vc
    }
    
   public override func popToViewController(_ viewController: UIViewController, animated: Bool) -> [UIViewController]? {
        self.poppingViewController = self.topViewController
        let array = super.popToRootViewController(animated: animated)
        // vc != self.topViewController
        self.fixClickBackIssue()
        return array
    }
    
    public override func popToRootViewController(animated: Bool) -> [UIViewController]? {
        self.poppingViewController = self.topViewController
        let array = super.popToRootViewController(animated: animated)
        // vc != self.topViewController
        self.fixClickBackIssue()
        return array
    }
    
    public func fixClickBackIssue() {
        if #available(iOS 13.0, *) {
            return
        }
        if #available(iOS 11.0, *) {
            // fix：ios 11，12，当前后两个页面的 barStyle 不一样时，点击返回按钮返回，前一个页面的标题颜色响应迟缓或不响应
            if let coordinator = self.transitionCoordinator, coordinator.isInteractive {
                self.navigationBar.barStyle = self.topViewController?.llBarStyle ?? UINavigationBar.appearance().barStyle
                self.navigationBar.titleTextAttributes = self.topViewController?.llTitleTextAttributes
            }
        }
    }
    
    
    public func updateNavigationBarForViewController(_ vc: UIViewController) {
        self.updateNavigationBarAlphaForViewController(vc)
        self.updateNavigationBarColorOrImageForViewController(vc)
        self.updateNavigationBarShadowImageIAlphaForViewController(vc)
        self.updateNavigationBarAnimatedForViewController(vc)
    }
    
    public func updateNavigationBarAlphaForViewController(_ vc: UIViewController) {
        if let _ = vc.llComputedBarImage {
            self.llNavigationBar?.fakeView?.alpha = 0
            self.llNavigationBar?.backgroundImageView?.alpha = vc.llBarAlpha
        } else {
            self.llNavigationBar?.fakeView?.alpha = vc.llBarAlpha
            self.llNavigationBar?.backgroundImageView?.alpha = 0
        }
        self.llNavigationBar?.shadowImageView?.alpha = vc.llComputedBarShadowAlpha
    }
    
    public func updateNavigationBarColorOrImageForViewController(_ vc: UIViewController) {
        self.llNavigationBar?.barTintColor = vc.llComputedBarTintColor
        self.llNavigationBar?.backgroundImageView?.image = vc.llComputedBarImage
    }
    
    public func updateNavigationBarShadowImageIAlphaForViewController(_ vc: UIViewController) {
        self.llNavigationBar?.shadowImageView?.alpha = vc.llComputedBarShadowAlpha
    }
    
    public func updateNavigationBarAnimatedForViewController(_ vc: UIViewController) {
        self.llNavigationBar?.tintColor = vc.llTintColor
        self.llNavigationBar?.barStyle = vc.llBarStyle
        self.llNavigationBar?.titleTextAttributes = vc.llTitleTextAttributes
        
        if #available(iOS 11.0, *) {
            if self.poppingViewController == nil {
                var index = -1
                if !(self.transitional) {
                    for (idx,obj) in self.children.enumerated() {
                        if obj == vc {
                            index = idx
                            return
                        }
                    }
                }
                if index > -1 && index < self.children.count {
                    let backItemVC = self.children[index]
                    if var backItem = backItemVC.navigationItem.backBarButtonItem {
                        backItem = UIBarButtonItem.init()
                        if let storedBackItem = backItemVC.llBackBarButtonItem {
                            backItem.title = storedBackItem.title
                        }else {
                            backItem.title = self.llNavigationBar?.backButtonLabel?.text
                        }
                        backItem.tintColor = vc.llTintColor
                        backItemVC.navigationItem.backBarButtonItem = backItem
                    }
                }
            }
        }
    }
    
    public func showFakeBarFrom(_ from: UIViewController, _ to: UIViewController) {
        UIView.setAnimationsEnabled(false)
        self.llNavigationBar?.fakeView?.alpha = 0
        self.llNavigationBar?.shadowImageView?.alpha = 0
        self.llNavigationBar?.backgroundImageView?.alpha = 0
        self.showFakeBar(from)
        self.showFakeBarTo(to)
        UIView.setAnimationsEnabled(true)
    }
    
    public func showFakeBar(_ from: UIViewController) {
        if self.fromFakeImageView == nil {
            self.fromFakeImageView = UIImageView()
        }
        self.fromFakeImageView?.image = from.llComputedBarImage;
        self.fromFakeImageView?.alpha = from.llBarAlpha
        self.fromFakeImageView?.frame = self.fakeBarFrameForViewController(from)
        from.view.addSubview(fromFakeImageView!)
        
        if self.fromFakeBar == nil {
            let blurEffect = UIBlurEffect(style: .light)
            let blurView = UIVisualEffectView(effect: blurEffect)
            fromFakeBar = blurView
        }
        self.fromFakeBar?.subviews.last?.backgroundColor = from.llComputedBarTintColor;
        self.fromFakeBar?.alpha = (from.llBarAlpha == 0 || from.llComputedBarImage != nil) ? 0.01 : from.llBarAlpha
        if from.llBarAlpha == 0 || from.llComputedBarImage != nil {
            self.fromFakeBar?.subviews.last?.alpha = 0.01
        }
        self.fromFakeBar?.frame = self.fakeBarFrameForViewController(from)
        from.view.addSubview(fromFakeBar!)
        
        if fromFakeShadow == nil {
            self.fromFakeShadow = UIImageView.init(image: self.llNavigationBar?.shadowImageView?.image)
            fromFakeShadow?.backgroundColor = self.llNavigationBar?.shadowImageView?.backgroundColor
        }
        self.fromFakeShadow?.alpha = from.llComputedBarShadowAlpha;
        self.fromFakeShadow?.frame = self.fakeShadowFrameWithBarFrame(self.fromFakeBar!.frame)
        from.view.addSubview(fromFakeShadow!)
    }
    
    public func showFakeBarTo(_ to: UIViewController) {
        if self.toFakeImageView == nil {
            self.toFakeImageView = UIImageView()
        }
        self.toFakeImageView?.image = to.llComputedBarImage;
        self.toFakeImageView?.alpha = to.llBarAlpha;
        self.toFakeImageView?.frame = self.fakeBarFrameForViewController(to)
        to.view.addSubview(toFakeImageView!)
        
        if self.toFakeBar == nil {
            let blurEffect = UIBlurEffect(style: .light)
            let blurView = UIVisualEffectView(effect: blurEffect)
            toFakeBar = blurView
        }
        self.toFakeBar?.subviews.last?.backgroundColor = to.llComputedBarTintColor;
        self.toFakeBar?.alpha = to.llComputedBarImage != nil ? 0 : to.llBarAlpha;
        self.toFakeBar?.frame = self.fakeBarFrameForViewController(to)
        to.view.addSubview(toFakeBar!)
        
        
        if toFakeShadow == nil {
            self.toFakeShadow = UIImageView.init(image: self.llNavigationBar?.shadowImageView?.image)
            toFakeShadow?.backgroundColor = self.llNavigationBar?.shadowImageView?.backgroundColor
        }
        self.toFakeShadow?.alpha = to.llComputedBarShadowAlpha
        self.toFakeShadow?.frame = self.fakeShadowFrameWithBarFrame(self.toFakeBar!.frame)
        to.view.addSubview(toFakeShadow!)
    }
    
    public func fakeBarFrameForViewController(_ vc: UIViewController) -> CGRect {
        guard let back = self.llNavigationBar?.subviews[0] else {
            return CGRect.zero
        }
        guard var frame = self.llNavigationBar?.convert(back.frame, to: vc.view) else {
            return CGRect.zero
        }
        frame.origin.x = 0
        if (vc.edgesForExtendedLayout.rawValue & UIRectEdge.top.rawValue) == 0 {
            frame.origin.y = -frame.size.height
        }
        
        // fix issue for pushed to UIViewController whose root view is UIScrollView.
        if vc.view.isKind(of: UIScrollView.self) {
            if let scrollview = vc.view as? UIScrollView {
                scrollview.clipsToBounds = false
                if scrollview.contentOffset.y == 0 {
                    frame.origin.y = -frame.size.height
                }
            }
        }
        return frame
    }
    
    public func fakeShadowFrameWithBarFrame(_ frame: CGRect) -> CGRect {
        return CGRect.init(x: frame.origin.x, y: frame.size.height + frame.origin.y - 0.5, width: frame.size.width, height: 0.5)
    }
    
    
    public func clearFake() {
        fromFakeBar?.removeFromSuperview()
        toFakeBar?.removeFromSuperview()
        fromFakeShadow?.removeFromSuperview()
        toFakeShadow?.removeFromSuperview()
        fromFakeImageView?.removeFromSuperview()
        toFakeImageView?.removeFromSuperview()
        fromFakeBar = nil
        toFakeBar = nil
        fromFakeShadow = nil
        toFakeShadow = nil
        fromFakeImageView = nil
        toFakeImageView = nil
    }
    
    public func resetSubviewsInNavBar(_ navBar: UINavigationBar) {
        if #available(iOS 11, *) {
            // empty
        } else {
            // Workaround for >= iOS7.1. Thanks to @boliva - http://stackoverflow.com/posts/comments/34452906
            for (_,subview) in navBar.subviews.enumerated() {
                if subview.alpha < 1.0 {
                    UIView.animate(withDuration: 0.25) {
                        subview.alpha = 1.0
                    }
                }
            }
        }
    }
    
}
extension UINavigationController: UINavigationBarDelegate {
    public func navigationBar(_ navigationBar: UINavigationBar, shouldPop item: UINavigationItem) -> Bool {
        if self.viewControllers.count > 1 && self.topViewController?.navigationItem == item {
            if !(self.topViewController?.llBackInteractive == true && self.topViewController?.llClickBackEnabled == true) {
                if let nav = self as? LLNavigationController {
                    nav.resetSubviewsInNavBar(navigationBar)
                }
                return false
            }
        }
        return true
    }
}

